import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { CreateRoleDto, QueryRoleDto } from './role.dto'
import { Role } from './role.model';
import { RESPONSE_CODE } from "@/enums/code";

@Injectable()
export class RoleService {
  constructor(
    @InjectModel(Role)
    private roleModel: typeof Role,
  ) { }

  /**
   * 添加角色信息
   * @param ctx
   * @method post
   */
  async addRole(createRoleDto: CreateRoleDto) {
    await this.roleModel.create({
      ...createRoleDto,
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: [],
      msg: null,
    };
  }

  /**
   * 获取角色分页
   * @param ctx
   * @method get
   */
  async getRolePage(queryRoleDto: QueryRoleDto) {
    const { current, size } = queryRoleDto;
    const { count, rows } = await this.roleModel.findAndCountAll({
      where: {},
      order: [["roleSort", "ASC"]],
      offset: (Number(current) - 1) * Number(size),
      limit: Number(size),
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: {
        records: rows,
        total: count,
        size: Number(size),
        current: Number(current),
        pages: Math.ceil(count / Number(size)),
      },
      msg: null,
    };
  }

  /**
   * 获取角色列表
   * @param ctx
   * @method get
   */
  async getRoleList() {
    const roles = await this.roleModel.findAll();
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: roles,
      msg: null
    }
  }

  /**
   * 获取角色信息
   * @param ctx
   * @method post
   */
  async getRoleInfo(roleId: number) {
    const res = await this.roleModel.findOne({ where: { roleId } });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: {
        ...res?.dataValues,
        userList: [],
      },
      msg: null,
    };
  }

  /**
   * 通用方法
   * @param methods 方法
   * @param query query 条件
   * @returns 
   */
  async publicMethods(methods: string, query: any) {
    return await this.roleModel[methods]({ ...query });
  }
}
